home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2335 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.4 KB

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Sat, 20 Jan 1996 19:20:47 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9601201820.AA01752@dxmint.cern.ch>
  8. References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: frigate.doc.ic.ac.uk!dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. ebennett@rust.net writes:
  14.  
  15. >Given some number, there is a neat trick to generate a mask which will
  16. >have exactly one bit set in it.  The bit set will be the least
  17. >significant non-zero bit in the original number:
  18. >
  19. >    mask = ~number & number;
  20. >
  21. >Now, if number contained a single non-zero bit (and is therefore a
  22. >power of 2),  mask will be equal to number.  Therefore:
  23. >
  24. >   if (number == (~number & number))
  25. >   {
  26. >        /* number is a power of 2 */
  27. >   }
  28. >
  29. >Try it, you'll like it!
  30.  
  31. I don't think so.  ~number & number will _always_ give 0.  -number & number
  32. will actually work, except for the case when number == 0.  That is,
  33. assuming a two's complement implementation.  On a one's complement or
  34. sign-magnitude implementation it won't work at all.
  35.  
  36. Yet another guy who makes a fool of himself because he's too lazy to
  37. test his solution before posting.
  38.  
  39. Dan
  40.